<?php

declare(strict_types=1);

namespace App\Model;

use Hyperf\DbConnection\Model\Model;
use Hyperf\DbConnection\Db;

/**
 * 用户推荐
 */
class UserRecommand extends Model
{
    protected $table = 'user_recommand';

    protected $fillable = [
        'user_id', 'rec_user_ids', 'flag'
    ];

    //已读
    const STATUS_UNREAD = 0;
    //未读
    const STATUS_READ = 1;

    /**
     * 初始化用户推荐
     */
//    static function init($userId = 0, $gender = -1, $limit = 6)
//    {
//        if (!$userId) return [];
//        $recUserIds = [];
//        // if (!check_dev_env()) {
//        //半小时已经推荐过的
//        $where = [
//            ['user_id', $userId],
//            ['created_at', '>', date('Y-m-d H:i:s', time() - 24 * 3600)]
//        ];
//
//        //
//        $startTime=microtime(true);
//
//        $items = self::where($where)->orderBy('id', 'desc')->select('rec_user_ids')->limit(10)->get()->toArray();
//        foreach ($items as $item) {
//            $uids = $item['rec_user_ids'] ? json_decode($item['rec_user_ids'], true) : [];
//            $uids && $recUserIds = array_merge($recUserIds, $uids);
//        }
//        $endTime=microtime(true);
//        echo '已推荐程序执行时间:'.($endTime - $startTime);
//        echo "\n";
//        // }
//
//        //排除自己
//        $role = $gender == 1 ? UserProfile::ROLE_USER : UserProfile::ROLE_HOST;
//
//        $startTime=microtime(true);
//        $recUsers = UserProfile::getNewUsersV1($role, $gender, 300);
//        $endTime=microtime(true);
//        echo '推荐程序执行时间:'.($endTime - $startTime);
//        echo "\n";
//        //去除特定渠道
//        // if (!config('busi.online_tip_enable')) {
//        $startTime=microtime(true);
//        $settings = SettingAppHidden::getSetting(SettingAppHidden::FUNC_PUSH);
//        $endTime=microtime(true);
//        echo '获取配置程序执行时间:'.($endTime - $startTime);
//        echo "\n";
//
//        $startTimeS=microtime(true);
//        if (!empty($settings)) {
//            $channel = [];
//            $version = [];
//
//            Db::enableQueryLog();
//
//            foreach ($settings as $setting) {
//                $channel = array_unique(array_merge($channel,$setting['channel']));
//                $version = array_unique(array_merge($version,[$setting['version']]));
//            }
//
//            UserRecommand::getExcludeUsers();
//
//            $startTime=microtime(true);
//            $excludeUsers = self::getExcludeUsersV1($channel,$version);
//            var_dump(Arr::last(Db::getQueryLog()));
//            $recUsers = array_diff($recUsers,$excludeUsers);
////            var_dump($resUsers);
//            $endTime=microtime(true);
//            echo '程序执行时间:'.($endTime - $startTime);
//            echo "\n";
//        }
//        $endTimeS=microtime(true);
//        echo '循环程序执行时间:'.($endTimeS - $startTimeS);
//        echo "\n";
//        // }
//
//        $recUsers = array_values(array_diff($recUsers, $recUserIds, array_merge([$userId], config('busi.kefu_uid'))));
//        $recUsers = array_slice($recUsers, 0, $limit);
//
//        //记录推荐的用户
////        self::create([
////            'user_id' => $userId,
////            'rec_user_ids' => json_encode($recUers),
////        ]);
//        return $recUsers;
//    }

    /**
     * 根据时间段来获取数据
     * @param $userId
     * @return array
     */
    public function getAlreadyRecommendByTime($userId): array
    {
        $recUserIds = [];

        //目前是24小时
        $where = [
            ['user_id', $userId],
            ['created_at', '>', date('Y-m-d H:i:s', time() - 24 * 3600)]
        ];

        $items = self::where($where)
            ->orderBy('id', 'desc')
            ->select('rec_user_ids')
            ->get()
            ->toArray();

        foreach ($items as $item) {
            $uids = $item['rec_user_ids'] ? json_decode($item['rec_user_ids'], true) : [];
            $recUserIds = array_unique(array_merge($recUserIds, $uids));
        }

        return $recUserIds ?? [];
    }

    /**
     * 排除的用户
     */
    static function getExcludeUsers($channels = [], $version = '', $startTime = '', $endTime = '')
    {
        $where = [];
        if ($startTime) $where[] = ['created_at', '>=', $startTime];
        if ($endTime) $where[] = ['created_at', '<', $endTime];
        if ($version) $where[] = ['version', $version];
        if ($channels) return User::whereIn('cur_channel', $channels)->where($where)->pluck('id')->toArray();
        else return User::where($where)->pluck('id')->toArray();
    }

    /**
     * 排除的用户
     * @param array $channels
     * @param array $version
     * @param string $startTime
     * @param string $endTime
     * @return array
     */
    public function getExcludeUsersV1(array $channels = [], array $version = [], string $startTime = '', string $endTime = ''): array
    {
        $where = [];
        if ($startTime) $where[] = ['created_at', '>=', $startTime];
        if ($endTime) $where[] = ['created_at', '<', $endTime];
        if ($channels) {
            return Db::table('user')
                ->whereIn('cur_channel', $channels)
                ->whereIn('version', $version)
                ->where($where)
                ->pluck('id')
                ->toArray();
        } else {
            return Db::table('user')
                ->whereIn('version', $version)
                ->where($where)
                ->pluck('id')
                ->toArray();
        }
    }

    /**
     * 排除的用户
     */
    static function getExcludeUsersCity($channels = [], $version = '', $startTime = '', $endTime = '', $city = [])
    {

        $user = Db::table('user')->join('user_profile', function ($join) use ($channels, $version, $startTime, $endTime, $city) {
            $where = [];
            if ($startTime) $where[] = ['user.created_at', '>=', $startTime];
            if ($endTime) $where[] = ['user.created_at', '<', $endTime];
            if ($version) $where[] = ['user.app_version', $version];
            $join->on('user.id', '=', 'user_profile.user_id');
            if (!empty($where)) $join->where($where);
            if ($channels) {
                $join->whereIn('user.cur_channel', $channels);
            }

            if(!empty($city)){
                $join->whereIn('user_profile.locate_city',$city);
            }
        })->limit(500)->pluck('user.id')->toArray();

       return $user;

    }
}
